package com.zeus.thread;

import java.util.concurrent.*;

/**
 * zeus thread pool
 */
public class ZeusThreadPool {
    private String threadNamePrefix; //线程前缀
    private int corePoolSize; //核心线程数
    private int maxPoolSize; //最大线程数
    private int queueCapacity; //等待队列
    private int keepAliveSeconds; //线程保存时间 单位 seconds
    // 创建固定线程数的线程池
    private ExecutorService executorService;

    public ExecutorService getExecutorService() {
        return executorService;
    }

    public ZeusThreadPool(String threadNamePrefix, int corePoolSize, int maxPoolSize, int queueCapacity, int keepAliveSeconds) {
        this.threadNamePrefix = threadNamePrefix;
        this.corePoolSize = corePoolSize;
        this.maxPoolSize = maxPoolSize;
        this.queueCapacity = queueCapacity;
        this.keepAliveSeconds = keepAliveSeconds;
        executorService = new ThreadPoolExecutor(corePoolSize, maxPoolSize,
                keepAliveSeconds, TimeUnit.MILLISECONDS,
                this.createQueue(queueCapacity),
                new ZeusCustomizableThreadFactory(this.threadNamePrefix));
    }


    private BlockingQueue createQueue(int queueCapacity) {
        return (BlockingQueue)(queueCapacity > 0?new LinkedBlockingQueue(queueCapacity):new SynchronousQueue());
    }

    /**
     * 线程池销毁
     */
    public void destroy() {
        if (executorService != null) {
            executorService.shutdown();
        }
    }

    public String getThreadNamePrefix() {
        return threadNamePrefix;
    }

    public void setThreadNamePrefix(String threadNamePrefix) {
        this.threadNamePrefix = threadNamePrefix;
    }

    public int getCorePoolSize() {
        return corePoolSize;
    }

    public void setCorePoolSize(int corePoolSize) {
        this.corePoolSize = corePoolSize;
    }

    public int getMaxPoolSize() {
        return maxPoolSize;
    }

    public void setMaxPoolSize(int maxPoolSize) {
        this.maxPoolSize = maxPoolSize;
    }

    public int getQueueCapacity() {
        return queueCapacity;
    }

    public void setQueueCapacity(int queueCapacity) {
        this.queueCapacity = queueCapacity;
    }

    public int getKeepAliveSeconds() {
        return keepAliveSeconds;
    }

    public void setKeepAliveSeconds(int keepAliveSeconds) {
        this.keepAliveSeconds = keepAliveSeconds;
    }
}
